package com.hhit.zhgd.domain.excelimport

import cn.hutool.core.collection.CollUtil
import com.hhit.zhgd.domain.entity.ZhgdArchiveSituation
import java.util.function.Supplier
import java.util.stream.Collectors

object CatalogHierarchyBuilder {

    fun buildCatalogHierarchy(dataList: List<ArchiveSituationImportNewParam>): List<CatalogNode>? {
        val parentSet = LinkedHashSet<String?>()
        for (archiveSituationImportNewParam in dataList) {
            parentSet.add(archiveSituationImportNewParam.oneLevelCatalog)
        }

        val collect = dataList.groupBy {
            it.oneLevelCatalog
        }.mapValues {
            it.value.toCollection(mutableListOf())
        }.toMap(LinkedHashMap())

        val rootNodes: MutableList<CatalogNode> = ArrayList()
        for (parentKeySet in parentSet) {
            val catalogNode = CatalogNode(catalogName = parentKeySet)
            val child: MutableList<CatalogNode> = CollUtil.newArrayList()
            val archiveSituationImportNewParams = collect[parentKeySet]!!
            for (archiveSituationImportNewParam in archiveSituationImportNewParams) {
                val childCatalogNode = CatalogNode(catalogName = archiveSituationImportNewParam.twoLevelCatalog)
                child.add(childCatalogNode)
                catalogNode.children = child
            }
            rootNodes.add(catalogNode)
        }
        return rootNodes
    }

    fun buildCatalogHierarchyFromDB(dataList: List<ZhgdArchiveSituation>): List<CatalogNode>? {
        val dataMap = dataList.groupBy {
            it?.parentId
        }.mapValues { it.value.toCollection(mutableListOf()) }
            .toMap(LinkedHashMap())

        val roots: MutableList<CatalogNode> = ArrayList()
        if (dataMap?.containsKey(-1)==true) {
            for (data in dataMap[-1]!!) {
                roots.add(buildTree(data!!, dataMap))
            }
        }
        return roots
    }

    private fun buildTree(data: ZhgdArchiveSituation, dataMap: Map<Int?, List<ZhgdArchiveSituation>>): CatalogNode {
        val node = CatalogNode(catalogName = data.type, id = data.id, fileAddress = data.fileAddress)
        if (dataMap.containsKey(data.id)) {
            val children: MutableList<CatalogNode> = ArrayList()
            for (childData in dataMap[data.id]!!) {
                children.add(buildTree(childData, dataMap))
            }
            node.children = children
        }
        return node
    }
}